import React, {Component, Children} from 'react'
import { routerShape } from 'react-router';
import {inject, observer} from 'mobx-react';
import {observable,action,toJS} from 'mobx';
import { Tabs, Modal, Button, Table,message} from 'antd'
import WeaCircleImage from "../wea-circle-image"
import { WeaRichText } from 'ecCom'
import CommentList from "./CommentList"
import WorkRecordList from "./WorkRecordList"
import CommentBar from "./CommentBar"
import ComVar from "../ComVar"
import WeaUtils from "../wea-utils"
import * as Util from '../../../../util/index'
import Dict from '../wea-comment-dict';
const TabPane = Tabs.TabPane
const Confirm = Modal.confirm;
const {  ComeFrom} = ComVar
const {DateFormat} = WeaUtils

import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
const mirror = Dict.bottomBarMirror;
@inject('checkMatterStore')
@observer

class CommentContainer extends Component {
    static contextTypes = {
        router: routerShape
    }

    constructor(props) {
        super(props)
        this.state = {
            showWorkRecord: false,
            showScore: false,

            modalPublicViewVisible: false,

            commenting: false,
            authRange: [],
            editing: false,

            showEdit: false,
            showComment: false,
            isRemind: false
        }
        this.onTempletChange = this.onTempletChange.bind(this);
    }

    componentDidMount() {
        let dom = ReactDOM.findDOMNode(this);
        WeaUtils.imgZoom(dom, ".g-mbwc-normal");
    }

    componentDidUpdate() {
        let dom = ReactDOM.findDOMNode(this);
        WeaUtils.imgZoom(dom, ".g-mbwc-normal");
    }
    componentWillUnmount(){
        // this.setState({showWorkRecord: false})
    }
    render() {
        let {showScore, showWorkRecord, commenting, editing, authRange, showEdit, showComment} = this.state,
            {
                _key, checkMatterStore,
                children, blogId,  isLast, currentUser = {}, date = "", user, type,taskname,
                authority, isAgree, content, defaultTemplate,
                comments = [],
               isCanEdit,
                isHasLocation, isManagerScore,  weiboCKEditorConfig,
                hasEditor, hasImage, hasScroll,comment,showSlideEdit
            } = this.props
        let customers = [],
            workflows = [],
            cooperations = [];
        content || (content = defaultTemplate.tempContent);
        const workRecords = [
            {name: getLabel(33569,"流程"), data: workflows, count: workflows.length},
            {name: getLabel(30047,"协作"), data: cooperations, count: cooperations.length}
        ]
        //anruo test table
        const publics = []
        for (let i = 0; i < 100; i++) {
            publics.push({
                type: `部门${i}`,
                content: `需求分析${i}`,
                level: `${i} - 100`
            })
        }

		this.ckeId = '';
        let ckeId = "";
        if ( user.id) {
            if (blogId) {
                ckeId = `wea_ckeditor_weibo_${user.id}_${blogId || ""}`
            } else {
                ckeId = `wea_ckeditor_weibo_${user.id}_anruo_${_key}`
            }
            this.ckeId = ckeId;
        }

        //暂时接入过来 zxt
        let bottomBarConfig = [];

        weiboCKEditorConfig && weiboCKEditorConfig.map(cg => {
        	cg.name === 'dialogs' && cg.items.map(item => {
	        	let obj = {
	        		isBlog: true,
	        		name: 'Browser',
	        		show: <div className="wea-cb-item">
	                    <span className={`wea-cbi-icon ${mirror[item].icon}`}/>
	                    <span className="wea-cbi-text">{mirror[item].nameFunc()}</span>
	                </div>,
	        		type: mirror[item].type,
	        		title: mirror[item].nameFunc(),
	        		isSingle: item === 'Templet',
	        	};
	        	if(item === 'Templet') obj.onToolsChange = this.onTempletChange
	        	bottomBarConfig.push(obj);
	        })
        	cg.name === 'uploads' && cg.items.map(item => {
	        	bottomBarConfig.push({
	        		isBlog: true,
	        		name: 'Upload',
	        		show: <div className="wea-cb-item">
	        	        <span className='wea-cbi-icon icon-blog-Enclosure'/>
	        	        <span className="wea-cbi-text">{getLabel(387321,"附件")}</span>
	        	    </div>,
	        		uploadId: 'webo_edit',
	        		uploadUrl: `${item.Attachment.uploadUrl}?category=${item.Attachment.position}`,
	        		category: item.Attachment.position,
	        		maxUploadSize: item.Attachment.maxSize,
	        		style: {display: "inline-block"}
	        	})
	        })
        })
      let bottomBarRight = {
		width: 155,
        Component: [
			<span className="g-rich-text-toolbar-bottom-item" style={{position: "relative"}}>
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oy8pd2@publish`} className="g-button-release" onClick={this.publishWeibo.bind(this, ckeId)}>
					<span><span className="icon-coms-Release" /><span>{getLabel(131302,"发布")}</span></span>
				</Button>
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fg2af9@cancel`} onClick={this.cancelWeibo.bind(this, ckeId + "_edit")} style={{marginLeft: '8px'}}>{getLabel(31129,"取消")}</Button>
			</span>
        ]
      };
        //评论列表
        return (
            <div>
                <div
                    style={{display: (editing ? "none" : "")}}
                    className={'wea-mbw-container wea-mbw-container-' + (isLast ? 'last' : 'other')}
                >
                    <WeaCircleImage ecId={`${this && this.props && this.props.ecId || ''}_WeaCircleImage@xcfgje`}
                        name={user.name}
                        source={user.source}
                        diameter={40}
                        src={user.src}
                        style={{
                            margin: "0 6px 0 10px",
                            position: "absolute",
                            display: (hasImage ? "inline-block" : "none")
                        }}
                    />

                    {!showEdit ?
                        <div style={{marginLeft: (hasImage ? "56px" : "0")}}>
                        <div className="wea-mbwc-top" style={{marginTop: (!hasImage ? "-10px" : "0")}}>
                            <span
                                className="wea-mbwct-item wea-mbwct-name"
                            >
                                <a href={`javaScript:openhrm(${user.id});`} onClick={e => window.pointerXY(e)}  >{user.name || ""}</a>
                                <span style={{color: "#ccc",paddingLeft: "10px"}}>{user.source || ""}</span>
                                    <span style={{color: "#ccc",paddingLeft: "10px"}}>{user.instructType=="1"?"批示":(user.instructType=="0"?"反馈":"")}</span>
                                    <span style={{color: "#ccc",paddingLeft: "10px"}}>{user.instructType=="0"?"("+taskname+")":""}</span>
                            </span>
                        </div>
                        <div style={{padding: (!hasImage ? "0 12px 0 12px" : "0")}}>

                            {Children.only(children)}
                            {isHasLocation == '1' ?
                                <div style={{margin: "15px 0 0 10px", fontSize: "14px"}}>
                                    <a onClick={this.openMap}><span className="icon-coms-position" style={{marginRight: "4px"}}/>{getLabel(384395,"查看地图")}</a>
                                </div> : undefined
                            }
                            <div className="wea-mbwc-bottom">
                            <span
                                className="wea-mbwcb-item wea-mbwcb-left">{DateFormat(date, "yyyy年MM月dd日 HH:mm")}</span>
                                <div className="wea-mbwcb-item wea-mbwcb-right">
                                    {
                                        isCanEdit && showSlideEdit ? (
                                            <span
                                                className="wea-mbwcbr-item icon-blog-Pay"
                                                onClick={() => this.onEditClick(ckeId + "_edit", content)}
                                            ><span style={{fontSize: "12px"}}>&nbsp;{getLabel(93,"编辑")}</span></span>
                                        ) : ""
                                    }
                                    {/* 编辑/评论 */}
                                    {
                                       showSlideEdit && (<span
                                            className="wea-mbwcbr-item icon-blog-Comment"
                                            onClick={this.onCommentClick.bind(this, ckeId + "_comment")}
                                            style={(commenting ? {color: "#32a8ff", cursor: "default"} : {
                                                color: "#484848",
                                                cursor: "pointer"
                                            })}
                                        ><span style={{fontSize: "12px"}}>&nbsp;{getLabel(675,comment[0])}</span></span>)
                                    }
                                </div>
                            </div>
                            <CommentList ecId={`${this && this.props && this.props.ecId || ''}_CommentList@ace12r`}
                                data={comments || []}
                                blogId={blogId}
                                checkMatterStore={checkMatterStore}
                                user={user}
                                hasEditor={hasEditor}
                                weiboCKEditorConfig={weiboCKEditorConfig}
                                showSlideEdit={showSlideEdit}
                            />
                            {
                                /* 展示流程/协作 */
                                showWorkRecord ? (
                                    <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@dsfbf0`} type="card" className="wea-nbwc-workRecord" animated={false}>
                                        {
                                            workRecords.map(
                                                (item, key) => {
                                                    return (
                                                        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@t5f92r@${key + 1}`}
                                                            tab={item.name + ' ' + (item.count ? '(' + item.count + ')' : '')}
                                                            key={key + 1}>
                                                            <WorkRecordList ecId={`${this && this.props && this.props.ecId || ''}_WorkRecordList@m41jn1@${key + 1}`} data={item.data || []}/>
                                                        </TabPane>
                                                    )
                                                }
                                            )
                                        }
                                    </Tabs>
                                ) : null
                            }
                            {
                                ckeId && showComment ? (
                                    <div>
                                    	<div className='g-ckeditor-import-ecCom' style={{padding: "12px 10px 0 10px", minHeight: ComVar.commentMinHeight+64}}>
	                                    	<WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@11silo`}
							            		id={ckeId + "_comment"}
							                    ref={ckeId + "_comment"}
							                    value={""}
							                    ckConfig={{
							                    	toolbar:[
											            { name: 'document', items: [ 'Source'] },
											            { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
											            { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
											            { name: 'colors', items: [ 'TextColor' ] },
											            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
											            { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] }
											        ],
											        extraPlugins: 'autogrow',
							                        height: ComVar.commentMinHeight,
							                        autoGrow_minHeight:ComVar.commentMinHeight,
							                        autoGrow_maxHeight: 600,
							                        removePlugins: 'resize',
							                        uploadUrl: '/api/blog/fileupload/uploadimage',
							                    }}
							                    bottomBarConfig
							                    onChange={v=>{}}
							                    onStatusChange={s => {}}
							                    onToolsChange={Util.transfStr}
							            	/>
						            	</div>
                                        {/* weibo-list 评论、取消按钮 */}
                                        <CommentBar ecId={`${this && this.props && this.props.ecId || ''}_CommentBar@pvzra7`}
                                            checked={this.state.isPrivate}
                                            submitComment={this.submitComment.bind(this, ckeId + "_comment")}
                                            cancelComment={this.cancelComment.bind(this, ckeId + "_comment")}
                                            style={{margin: "12px 12px 10px 12px", display: (commenting ? "" : "none")}}
                                        />
                                    </div>
                                ) : <div/>
                            }
                        </div>
                    </div>
                    :''}
                </div>
                {
                    ckeId && showEdit ? (
                        <div className='g-ckeditor-import-ecCom'>
                            <div style={{minHeight: 251}}>
                                <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@myn2ij`}
                                    id={ckeId + "_edit"}
                                    ref={ckeId + "_edit"}
                                    value={content}
                                    ckConfig={{
                                        toolbar:[
                                            { name: 'document', items: [ 'Source'] },
                                            { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
                                            { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
                                            { name: 'colors', items: [ 'TextColor' ] },
                                            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
                                            { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] }
                                        ],
                                        extraPlugins: 'autogrow',
                                        height:150,
                                        autoGrow_minHeight: 150,
                                        autoGrow_maxHeight: 600,
                                        removePlugins: 'resize',
                                        uploadUrl: '/api/blog/fileupload/uploadimage',
                                    }}
                                    bottomBarConfig={ bottomBarConfig }
                                    bottomBarRight={bottomBarRight}
                                    onChange={v=>{}}
                                    onStatusChange={s => {}}
                                    onToolsChange={Util.transfStr}
                                />
                            </div>

                        </div>
                    ) : <div/>
                }
            </div>
        )
    }
    onTempletChange(name, ids, list, type){
        // Util.templetChange(this.refs[this.ckeId + "_edit"].getData(),v =>this.refs[this.ckeId + "_edit"].setData(v), name, ids, list, type)
        if(this.refs[this.ckeId + "_edit"].wrappedInstance){
            Util.templetChange(this.refs[this.ckeId + "_edit"].getData(),v =>this.refs[this.ckeId + "_edit"].setData(v), name, ids, list, type)

        }else{
            Util.templetChange(this.refs[this.ckeId + "_edit"].getData(),v =>this.refs[this.ckeId + "_edit"].setData(v), name, ids, list, type)

        }
    }
    // onScoreChange = (value) => {
    //     let {func, blogId, workdate, user} = this.props
    //     const {setScore} = this.props.checkMatterStore
    //
    //     setScore({
    //         discussId: blogId,
    //         score: value,
    //         workdate: workdate,
    //         userId: user.id
    //     })
    // }
    onAuthRange = (authRange) => {
        this.setState({authRange: authRange})
    }
    //点击评论
    onCommentClick = (ckeId) => {
        const {user} = this.props;
        let {getInstype} = this.props.checkMatterStore;
        user.instructType == "1"?getInstype("3") : user.instructType == "0" ? getInstype("2") : null
        if (!this.state.commenting) {
            this.setState(
                {showComment: true, commenting: true}
            )
        }
    }

    submitComment = (ckeId) => {
        let ckref = this.refs[ckeId];
        if(this.refs[ckeId].wrappedInstance){
            ckref = this.refs[ckeId].wrappedInstance
        }else{
            ckref = this.refs[ckeId]

        }
        if (!ckref.checkMode()) {
            message.error(getLabel('384536',"不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式"));
            return;
        }
        let {func, blogId,  user} = this.props
        let {editWeibo,taskId,instype,pageindex,pagesize} = this.props.checkMatterStore;
        let params = {
            content: this.refs[ckeId].getData() || '',
            taskId:taskId,
            instype: instype,
        }
        if(this.refs[ckeId].wrappedInstance){
            params = {
                content: this.refs[ckeId].wrappedInstance.getData() || '',
                bediscussantId: user.id,
                commentType: this.state.isPrivate ? 1 : 0,
                comefrom: ComeFrom.pc
            }
        }
        if (blogId) params.instructTopid = blogId
        editWeibo(
            params,
            {
                "taskId":taskId,
                "pageindex":pageindex,
                "pagesize":pagesize
            }
        );
        this.setState({commenting: false, showComment: false,isPrivate:false})
    }

    cancelComment = (ckeId) => {
        // this.refs[ckeId].removeEditor()
        if(this.refs[ckeId].wrappedInstance){
            this.refs[ckeId].wrappedInstance.removeEditor();

        }else{
            this.refs[ckeId].removeEditor();

        }
        this.setState({commenting: false, showComment: false,isPrivate:false})
    }
    onEditClick = (ckeId, content) => {
        if (!this.state.editing) {
            this.setState(
                {showEdit: true, editing: true}
            )
        }
    }

    cancelWeibo = (ckeId) => {
        // this.refs[ckeId].removeEditor()
        if(this.refs[ckeId].wrappedInstance){
            this.refs[ckeId].wrappedInstance.removeEditor();

        }else{
            this.refs[ckeId].removeEditor();

        }
        this.setState({editing: false, showEdit: false})
    }
    /* 编辑发布 */
    publishWeibo = (ckeId) => {
        let {editWeibo,taskId,pagesize,pageindex} = this.props.checkMatterStore
        let {func, blogId,  user} = this.props,
            {authRange} = this.state
        let ckref = this.refs[ckeId + '_edit'];
        if(this.refs[ckeId + '_edit'].wrappedInstance){
            ckref = this.refs[ckeId + '_edit'].wrappedInstance;
        }
        if (!ckref.checkMode()) {
            message.error(getLabel('384536',"不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式"));
            return;
        }
        let params = {
            content: this.refs[ckeId + '_edit'].getData()
        }
        if (blogId) params.id = blogId
        editWeibo(
            params,
            {
                "taskId":taskId,
                "pageindex":this.props.checkMatterStore.pageindex,
                "pagesize":this.props.checkMatterStore.pagesize
            }
        );
        this.setState({editing: false, showEdit: false});
    }
    setModalPublicViewVisible = (modalPublicViewVisible) => {
        this.setState({modalPublicViewVisible: modalPublicViewVisible})
    }

    onPublicViewShowSizeChange = (current, pageSize) => {
    }
    onPublicViewChange = (current) => {

    }

    onPublicViewShowTotalChange = (total) => {
        return `共 ${total} 条`
    }
    openMap = () => {
        // this.refs.map.open();
        if(this.refs.map.wrappedInstance){
            this.refs.map.wrappedInstance.open()
        }else{
            this.refs.map.open()
        }
    }
}

export default CommentContainer
